package com.manning.readinglist;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
@RequestMapping("/")
//@ConfigurationProperties(prefix = "amazon")
public class ReadingListController {

    private ReadingListRepository readingListRepository;
    private AmazonProperties amazonConfig;
    private CounterService counterService;
    private GaugeService gaugeService;

	/**
	 * 注入 CounterService 和 GaugeService
	 * @param readingListRepository
	 * @param amazonConfig
	 * @param counterService
	 * @param gaugeService
	 */
	@Autowired
	public ReadingListController(ReadingListRepository readingListRepository,
								 AmazonProperties amazonConfig, @Qualifier("counterService") CounterService counterService,
								 @Qualifier("gaugeService") GaugeService gaugeService) {
		this.readingListRepository = readingListRepository;
    this.amazonConfig = amazonConfig;
    this.counterService = counterService;
    this.gaugeService = gaugeService;
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/fail")
	public void fail() {
	  throw new RuntimeException();
	}
	
	@ExceptionHandler(value=RuntimeException.class)
	@ResponseStatus(value=HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)
	public String error() {
	  return "error";
	}
	
	
	@RequestMapping(method=RequestMethod.GET)
	public String readersBooks(Reader reader, Model model) {
		List<Book> readingList = readingListRepository.findByReader(reader);
		if (readingList != null) {
			model.addAttribute("books", readingList);
			model.addAttribute("reader", reader);
			model.addAttribute("amazonID", amazonConfig.getAssociateId());
		}
		return "readingList";
	}

	/**
	 * addToReadingList() 方法每次处理请求时都会调用 counterService.increment("books.saved") 和 gaugeService.submit("books. last.saved") 来调整度量值。
	 * @param reader
	 * @param book
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public String addToReadingList(Reader reader, Book book) {
		book.setReader(reader);
		readingListRepository.save(book);
		// 增加 books.saved 的值
		counterService.increment("books.saved");
		// 记录 books.last.saved 的值
		gaugeService.submit("books.save.time", System.currentTimeMillis());
		return "redirect:/";
	}
	
}
